package com.seven.springboot.config;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.seven.springboot.datasource.DynamicDataSource;
import com.seven.springboot.enums.DatabaseType;

@Configuration // 该注解类似于spring配置文件
@MapperScan(basePackages = "com.seven.springboot.mapper")
public class MyBatisConfig {

	@Value("${mybatis.mapper-locations}")
	private String mapperLocations;
	
	@Value("${mybatis.type-aliases-package}")
	private String aliasesPackage;
	
	
	@Bean(name = "yinDataSource")
	@ConfigurationProperties(prefix = "jdbc.yin")
	public DataSource yinDataSource() {
		return DataSourceBuilder.create().build();
	}
	
	@Bean(name = "yangDataSource")
	@ConfigurationProperties(prefix = "jdbc.yang")
	public DataSource yangDataSource() {
		return DataSourceBuilder.create().build();
	}
	
	@Bean(name = "dataSource")
	@Qualifier
	public DynamicDataSource dataSource(@Qualifier("yinDataSource") DataSource yinDataSource,
                                        @Qualifier("yangDataSource") DataSource yangDataSource) {
		Map<Object, Object> targetDataSources = new HashMap<>();
		targetDataSources.put(DatabaseType.yin, yinDataSource);
		targetDataSources.put(DatabaseType.yang, yangDataSource);
		DynamicDataSource dataSource = new DynamicDataSource();
		dataSource.setTargetDataSources(targetDataSources);
		dataSource.setDefaultTargetDataSource(yangDataSource);   //默认采用paas
		return dataSource;
	}
	
	@Bean("sqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception {
		SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
		fb.setDataSource(ds);
		fb.setTypeAliasesPackage(aliasesPackage);
		fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
		return fb.getObject();
	}
	
	@Bean
	public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}
	
}
